//定时器
var timer = null;
// 非正文需要朗读的标签 逗号分隔
var speakTags = 'a,p,span,h1,h2,h3,h4,h5,h6,img,input,button,li,i';
// 标签朗读文本
var tagTextConfig = {
    a: '链接',
    'input[text]': '文本输入框',
    'input[password]': '密码输入框',
    button: '按钮',
    img: '图片',
    option: '选项'
};
// 正文拆分配置
var splitConfig = {
    // 内容分段标签名称
    unitTag: 'p',
    // 分隔正则表达式
    splitReg: /[,;，；。]/g,
    // 包裹标签名
    wrapTag: 'label',
    wrapCls: 'speak-lable',
    // 高亮样式
    hightlightCls: ''
    // hightStyle: 'background: #000!important;color: #fff!important'
};

var timerSpeak;
/**
 * 获取标签朗读文本
 * @param {HTMLElement} el 要处理的HTMLElement
 * @returns {String}   朗读文本
 */
function getTagText(el) {
    if (!el) return '';
    var res;

    var tagName = el.tagName.toLowerCase();

    var textChange = function (dom) {
        function getText(element) {
            var elementText;

            if (element.nodeName == '#text') {
                elementText = element.nodeValue;
            } else if (element.nodeName == 'IMG') {
                if (element.getAttribute('alt')) {
                    elementText = element.getAttribute('alt');
                } else if (element.getAttribute('title')) {
                    elementText = element.getAttribute('title');
                } else {
                    elementText = document.title;
                }
            } else {
                elementText = element.innerText || element.textContent;
            }
            return elementText;
        }
        var textMessage = '';

        if (dom.nodeName == 'IMG') {
            if (dom.parentNode.parentNode.nodeName == 'A' || dom.parentNode.nodeName == 'A') {
                textMessage = ABTConfig.language.textTips.textName.tagName1 + '' + getText(dom);
            } else {
                textMessage = ABTConfig.language.textTips.textName.tagName2 + '' + getText(dom);
            }
        } else if (dom.nodeName == 'OBJECT') {
            textMessage = ABTConfig.language.textTips.textName.tagName3 + '' + dom.getAttribute('title');
        } else if (dom.nodeName == 'SELECT') {
            textMessage = ABTConfig.language.textTips.textName.tagName4;
        } else if (dom.nodeName == 'INPUT') {
            var inputType = dom.getAttribute('type');
            switch (inputType) {
                case 'button':
                    textMessage = ABTConfig.language.textTips.textName.tagName5 + '' + dom.getAttribute('value');
                    break;
                case 'image':
                    textMessage = ABTConfig.language.textTips.textName.tagName6 + '' + dom.getAttribute('alt');
                    break;
                case 'submit':
                    textMessage = ABTConfig.language.textTips.textName.tagName7 + '' + dom.getAttribute('value');
                    break;
                case 'reset':
                    textMessage = ABTConfig.language.textTips.textName.tagName8 + '' + dom.getAttribute('value');
                    break;
                case 'file':
                    textMessage = ABTConfig.language.textTips.textName.tagName9 + '' + dom.getAttribute('title');
                    break;
                case 'password':
                    textMessage = ABTConfig.language.textTips.textName.tagName10 + '' + dom.getAttribute('title');
                    break;
                case 'radio':
                    textMessage = ABTConfig.language.textTips.textName.tagName11 + '' + dom.getAttribute('title');
                    break;
                case 'checkbox':
                    textMessage = ABTConfig.language.textTips.textName.tagName12 + '' + dom.getAttribute('title');
                    break;
                case 'text':
                    textMessage = ABTConfig.language.textTips.textName.tagName13 + '' + dom.getAttribute('title');
                    break;
            }
        } else if (dom.parentNode.parentNode.nodeName == 'A' || dom.parentNode.nodeName == 'A' || dom.nodeName == 'A') {
            var thisContent;
            if (dom.parentNode.parentNode.nodeName == 'A') {
                if (dom.parentNode.parentNode.getAttribute('title')) {
                    thisContent = dom.parentNode.parentNode.getAttribute('title');
                } else {
                    thisContent = dom.innerText || dom.textContent;
                }
            } else if (dom.parentNode.nodeName == 'A') {
                if (dom.parentNode.getAttribute('title')) {
                    thisContent = dom.parentNode.getAttribute('title');
                } else {
                    thisContent = dom.innerText || dom.textContent;
                }
            } else {
                if (dom.getAttribute('title')) {
                    thisContent = dom.getAttribute('title');
                } else {
                    thisContent = dom.innerText || dom.textContent;
                }
            }
            textMessage = ABTConfig.language.textTips.textName.tagName14 + '' + thisContent;
        } else if (
            dom.parentNode.nodeName == 'H1' ||
            dom.parentNode.nodeName == 'H2' ||
            dom.parentNode.nodeName == 'H3' ||
            dom.parentNode.nodeName == 'H4' ||
            dom.parentNode.nodeName == 'H5' ||
            dom.parentNode.nodeName == 'H6'
        ) {
            var thisContent = dom.innerText || dom.textContent;
            textMessage = ABTConfig.language.textTips.textName.tagName15 + '' + thisContent;
        } else {
            var thisContent = dom.innerText || dom.textContent;
            textMessage = ABTConfig.language.textTips.textName.tagName16 + '' + thisContent;
        }

        return textMessage;
    };



    // 处理input等多属性元素
    // switch (tagName) {
    //     case 'input':
    //         tagName += '[' + el.type + ']';
    //         break;
    //     case 'em':
    //         res = textChange(el);
    //         break;
    //     default:
    //         res = (tagTextConfig[tagName] || '文本') + (el.title || el.alt || el.innerText || '');
    //         break;
    // }
    res = textChange(el);
    return res;
}

/**
 * 获取完整朗读文本
 * @param {HTMLElement} el 要处理的HTMLElement
 * @returns {String}   朗读文本
 */
function getText(el) {
    if (!el) return '';
    return getTagText(el);
}

// 文本分隔
function splitConent($content) {
    $content = $($content);

    $content.find(splitConfig.unitTag).each(function (index, item) {
        var $item = $(item),
            text = $item.text();

        if (!text) return;

        // var html = $item.html(),
        // <p>这是一段测试文本，这里有个链接。<a>您好，可以点击此处进行跳转</a>还有其他内容其他内容容其他内容容其他内容，容其他内容。</p>
        // <p><div>这是一段测试文本，这里有个链接。<a>您好，可以点击此处进行跳转</a>还有其他内容其他内容容其他内容容其他内容，容其他内容。</div></p>
        // var html = '<div>这是一段测试文本，这里有个链接。<a>您好，可以点击此处进行跳转</a>还有其他内容其他内容容其他内容容其他内容，容其他内容。</div>',
        //     start = '',
        //     end = '';

        // 文本分段
        // var arr = $.map(html.split(splitConfig.splitReg), function (it) {
        //     // 含有标签则不处理
        //     if (!/<\/?\w+?>/.test(it) && it) {
        //         var wrap = document.createElement(splitConfig.wrapTag);
        //         wrap.className = splitConfig.wrapCls;
        //         wrap.innerHTML = it;
        //         it = wrap.outerHTML;
        //         return it;
        //     }
        //     return it;
        // });
        // 正则分隔就丢失了分隔符，因此不能用
        // 这里直接将分隔符替换为 </tag>分隔符<tag>的形式，最后再在首位补上开始和结束来处理
        // html = html.replace(splitConfig.splitReg, '</' + splitConfig.wrapTag + '>$&<' + splitConfig.wrapTag + '>');
        // 如果段落中的a标签中也存在分隔的符号，上面就破快结构了。。。
        var nodes = $item[0].childNodes;

        $.each(nodes, function (i, node) {
            switch (node.nodeType) {
                // text 节点
                case 3:
                    // 由于是文本节点，标签被转义了，后续再转回来
                    node.data =
                        '<' +
                        splitConfig.wrapTag +
                        '>' +
                        node.data.replace(
                            splitConfig.splitReg,
                            '</' + splitConfig.wrapTag + '>$&<' + splitConfig.wrapTag + '>'
                        ) +
                        '</' +
                        splitConfig.wrapTag +
                        '>';
                    break;
                // 元素节点
                case 1:
                    var innerHtml = node.innerHTML,
                        start = '',
                        end = '';
                    // 如果首尾还有直接标签，先去掉
                    var startResult = /^<\w+?>/.exec(innerHtml);
                    if (startResult) {
                        start = startResult[0];
                        innerHtml = innerHtml.substr(start.length);
                    }
                    var endResult = /<\/\w+?>$/.exec(innerHtml);
                    if (endResult) {
                        end = endResult[0];
                        innerHtml = innerHtml.substring(0, endResult.index);
                    }
                    // 更新内部内容
                    node.innerHTML =
                        start +
                        '<' +
                        splitConfig.wrapTag +
                        '>' +
                        innerHtml.replace(
                            splitConfig.splitReg,
                            '</' + splitConfig.wrapTag + '>$&<' + splitConfig.wrapTag + '>'
                        ) +
                        '</' +
                        splitConfig.wrapTag +
                        '>' +
                        end;
                    console.log(node);
                    break;
                default:
                    break;
            }
        });

        // 处理文本节点中被转义的html标签
        $item[0].innerHTML = $item[0].innerHTML
            .replace(new RegExp('&lt;' + splitConfig.wrapTag + '&gt;', 'g'), '<' + splitConfig.wrapTag + '>')
            .replace(new RegExp('&lt;/' + splitConfig.wrapTag + '&gt;', 'g'), '</' + splitConfig.wrapTag + '>');

        $item.find(splitConfig.wrapTag).addClass(splitConfig.wrapCls);
    });
}

// 写入高亮样式
//function createStyle() {
//    if (document.getElementById('speak-light-style')) return;

//    var style = document.createElement('style');
//    style.id = 'speak-light-style';
//    style.innerText = '.' + splitConfig.hightlightCls + '{' + splitConfig.hightStyle + '}';
//    document.getElementsByTagName('head')[0].appendChild(style);
//}

function createStyle() {
    if (document.getElementById('speak-light-style')) return;
    var style = document.createElement('style'); // style.id = 'speak-light-style';    style.setAttribute('id','speak-light-style');
    if ('styleSheet' in style) {
        style.setAttribute('type', 'text/css');
        style.styleSheet.cssText = '.' + splitConfig.hightlightCls + '{' + splitConfig.hightStyle + '}';
    } else {
        style.innerText = '.' + splitConfig.hightlightCls + '{' + splitConfig.hightStyle + '}';
    }
    document.getElementsByTagName('head')[0].appendChild(style);
}

// 头部工具条指读
$(document)
    .on('mouseenter', '#toolbarList i', function (e) {
        // console.log('s');
        var $target = $(e.target);

        if ($target.parents('.' + splitConfig.wrapCls).length || $target.find('.' + splitConfig.wrapCls).length) {
            return;
        }
        if (!toolbar.Function.continuous.continuous) {
            // 开始朗读

            if (!toolbar.Function.overSoundMode.overSoundModeState) {
                if (e.target.nodeName.toLowerCase() === 'img') {
                    // $target.css({
                    //     border: '2px solid #000'
                    // });
                    if ($target.parent().is('a')) {
                        speakText($target.parent().attr('title'));
                    } else {
                        speakText(getText(e.target));
                    }
                } else if (e.target.nodeName.toLowerCase() === 'i') {
                    if ($target.parent().is('a')) {
                        speakText($target.parent().attr('title'));
                    }
                } else {
                    $target.addClass(splitConfig.hightlightCls);
                    speakText(getText(e.target));
                }
            } else {
                return false;
            }
        }
    })
    .on('mouseleave', '#toolbarList i', function (e) {
        var $target = $(e.target);
        if ($(e.target).parents('.' + splitConfig.wrapCls).length || $target.find('.' + splitConfig.wrapCls).length) {
            return;
        }

        if (e.target.nodeName.toLowerCase() === 'img') {
            $target.css({
                border: 'none'
            });
        } else {
            $target.removeClass(splitConfig.hightlightCls);
        }
        if (!toolbar.Function.continuous.continuous) {
            // 停止语音
            stopSpeak();
        }
    });

function initEvent() {
    $(document)
        .on('mouseenter.speak-help', speakTags, function (e) {
            var $target = $(e.target);

            if ($target.parents('.' + splitConfig.wrapCls).length || $target.find('.' + splitConfig.wrapCls).length) {
                return;
            }
            if (!toolbar.Function.continuous.continuous) {
                // 开始朗读

                if (toolbar.Function.overSoundMode.overSoundModeState) {
                    if (e.target.nodeName.toLowerCase() === 'img') {
                        if ($target.parent().is('a')) {
                            speakText('图片链接' + $target.parent().attr('title'));
                        } else {
                            speakText(getText(e.target));
                        }
                    } else if (e.target.nodeName.toLowerCase() === 'i') {
                        if ($target.parent().is('a')) {
                            speakText($target.parent().attr('title'));
                        }
                    } else if (e.target.nodeName.toLowerCase() === 'a') {
                        if ($target.text().length === 0) {
                            speakText($target.attr('title'));
                        } else {
                            speakText(getText(e.target));
                        }
                    } else {
                        $target.addClass(splitConfig.hightlightCls);
                        speakText(getText(e.target));
                    }
                } else {
                    return false;
                }
            }
        })
        .on('mouseleave.speak-help', speakTags, function (e) {
            var $target = $(e.target);
            if (
                $(e.target).parents('.' + splitConfig.wrapCls).length ||
                $target.find('.' + splitConfig.wrapCls).length
            ) {
                return;
            }

            if (e.target.nodeName.toLowerCase() === 'img') {
                $target.css({
                    border: 'none'
                });
            } else {
                $target.removeClass(splitConfig.hightlightCls);
            }

            // 停止语音
            stopSpeak();
        });

    $(document)
        .on('mouseenter.speak-help', '.' + splitConfig.wrapCls, function (e) {
            var $this = $(this),
                text = getText(this);
            $this.addClass(splitConfig.hightlightCls);
            // 开始朗读
            speakText(text);
        })
        .on('mouseleave.speak-help', '.' + splitConfig.wrapCls, function (e) {
            var $this = $(this);
            $this.removeClass(splitConfig.hightlightCls);

            // 停止语音
            stopSpeak();
        });
}

function offEvent() {
    $(document).off('mouseenter.speak-help', speakTags).off('mouseleave.speak-help', speakTags);

    $(document)
        .off('mouseenter.speak-help', '.' + splitConfig.wrapCls)
        .off('mouseleave.speak-help', '.' + splitConfig.wrapCls);
}

// 开始朗读
function speakText(text, conread) {
    clearTimeout(timer);
    timer = setTimeout(function () {
        // if (window.SpeechSynthesisUtterance && window.speechSynthesis) {
        //     var speaker = new window.SpeechSynthesisUtterance();
        //     speaker.text = text;
        //     speaker.onerror = function (e) {
        //         baiduSpeak(text);
        //     };
        //     window.speechSynthesis.speak(speaker);
        // } else {
        //     baiduSpeak(text);
        // }

        baiduSpeak(text, conread);
    }, 500);
}

function baiduSpeak(text, conread) {
    $.ajax({
        url: toolbar.config.baiduaddress,
        type: 'post',
        data: {},
        dataType: 'json',
        success: function (msg) {
            soundManager.setup({
                url: './js/ABT/swf/',
                onready: function () {
                    var speed;

                    // console.log(toolbar.Function.speed.speed);
                    if (toolbar.Function.speed.speed === '中') {
                        speed = toolbar.config.speed.defaultSpeed;
                    } else if (toolbar.Function.speed.speed === '快') {
                        speed = toolbar.config.speed.highSpeed;
                    } else {
                        speed = toolbar.config.speed.lowSpeed;
                    }
                    stopSpeak();
                    var soundurl =
                        'http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=1&tok=' +
                        $.parseJSON(msg.custom.result).access_token +
                        '&tex="' +
                        encodeURI(text) +
                        '&vol=9&spd=' +
                        speed;
                    var mySound = soundManager.createSound({
                        id: new Date().getTime(),
                        url: soundurl,
                        onfinish: function () {
                            // once sound has loaded and played, unload and destroy it.
                            this.destruct(); // will also try to unload before destroying.
                            soundManager.stopAll();
                        }
                    });
                    mySound.play({
                        onfinish: function () {
                            $('.accfocus').removeClass('accfocus');
                            if (toolbar.Function.continuous.continuous && conread) {
                                if (toolbar.prenode) {
                                    toolbar.Function.readcontinu(toolbar.prenode);
                                } else {
                                    speakText('播报已完成', false);
                                    // setTimeout(function () {
                                    //     toolbar.Function.readcontinu();
                                    // }, 4000);
                                }
                            }

                            // once sound has loaded and played, unload and destroy it.
                            this.destruct(); // will also try to unload before destroying.
                        }
                    });
                }
            });
        },
        error: function (msg) {
            //console.log(msg);
        }
    });
}

//回车事件
$(document).bind('keypress', function (event) {
    if (event.keyCode == '13' && toolbar.Function.continuous.continuous) {
        $('.accfocus').click();
    }
});

// 停止朗读
function stopSpeak() {
    // console.log('s');
    clearTimeout(timer);
    soundManager.stopAll();
}

function startSoundMode() {
    // 创建样式
    createStyle();
    // 分隔正文内容
    splitConent($('.news-article-para'));
    // 初始化事件
    initEvent();
}

function startAllSoundMode() {
    clearReadedStatus();
    // speakText(readstr);
    //此处拼接需要朗读的内容html，可多个拼接（因为朗读内容不能包含JS内容，可能会导致转换失败，为了解决部分项目可能JS复杂，减少模板的改动量），注意ID在页面的顺序，否则可能读取不对应
    var readHtml = '';
    if (exist('read2')) {
        readHtml += document.getElementById('read2').innerHTML;
    }
    if (exist('read')) {
        readHtml += document.getElementById('read').innerHTML;
    }

    var bodyJson = html2json(readHtml);
    changeClassAndId({
        json: bodyJson
    });
}

function exist(id) {
    var s = document.getElementById(id);
    return !!s;
}

var toReadList = [];
var count = 0,
    timer = null;
var changeClassAndId = function (opt) {
    var json = opt.json,
        preId = opt.preId || '';
    var _this = this;
    var child = json.child;
    addPreId(child);
    function addPreId(child) {
        if (child && child.length) {
            $(child).each(function (index, node) {
                if (node.node === 'text' && $.trim(node.text)) {
                    if (node.attr) {
                    }
                    var txt = node.text;
                    var $result = getDom({
                        txt: txt
                    });

                    toReadList.push({
                        dom: $result,
                        txt: txt
                    });
                }
                if (node.child) {
                    // 此处自行判断是否要根据有没有hidden 的class来往下探取
                    addPreId(node.child);
                }
            });
        }
    }
    beginRead();
};

function beginRead() {
    if (count < toReadList.length) {
        var readObj = toReadList[count];

        // console.log(readObj);
        var $dom = readObj.dom,
            txt = readObj.txt;
        // 取消前一个的状态

        if (count > 0) {
            var $preDom = toReadList[count - 1].dom;
            if ($preDom) {
                $preDom.removeClass('reading');
            }
        }
        // reading
        // if ($dom) {
        //     $dom.addClass('reading');
        // }

        if (toolbar.Function.overSoundMode.overSoundModeState) {
            speakText(txt);
        } else {
            return false;
        }

        // 开始读取有个过程，所以这里加定时器
        setTimeout(function () {
            timer = setInterval(function () {
                if (!window.speechSynthesis.speaking) {
                    clearInterval(timer);
                    count++;
                    beginRead();
                }
            }, 1000 / 60);
        }, 400);
    }
}
var getDom = function (opt) {
    try {
        var txt = opt.txt;
        var domArr = $("*:contains('" + txt + "')");
        var result = '';
        for (var i = 0, len = domArr.length; i < len; i++) {
            if (domArr[i].innerText == txt && !$(domArr[i]).data('readed')) {
                $(domArr[i]).data('readed', 1);
                result = $(domArr[i]);
                break;
            }
        }
        return result;
    } catch (err) {
        return '';
    }

    // return $($("*:contains('" + txt + "')")[$("*:contains('" + txt + "')").length - 1]);
};

// 清空获取text状态，对应 getDom方法
function clearReadedStatus() {
    for (var i = 0, len = toReadList.length; i < len; i++) {
        var $dom = readObj.dom;
        $dom.data('readed', '');
    }
}
